package chaoyue.study.controller;

import org.springframework.core.io.FileUrlResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;

@RestController
public class DownloadController {

    /**
     * 返回下载文件流 使用Resource
     */
    @GetMapping("/download1")
    public ResponseEntity<Resource> download1() throws MalformedURLException {
        Resource resource = new FileUrlResource("/Users/chaoyue/Pictures/miku.jpg");
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "miku.jpg");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // 返回响应实体
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }

    /**
     * 返回下载文件流 使用InputStreamResource
     */
    @GetMapping("/download2")
    public ResponseEntity<InputStreamResource> downloadFile() throws Exception {
        // 创建输入流
        InputStream inputStream = new FileInputStream("/Users/chaoyue/Pictures/miku.jpg");
        // 创建输入流资源对象
        InputStreamResource resource = new InputStreamResource(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "miku.jpg");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // 返回响应实体
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }
}
